import { RequestTracker } from '../utils/requestTracker';
import TimingLog = App.TimingLog;

/**
 * 统计页面加载时间
 */
export class Timing {
    private readonly requestTracker: RequestTracker;
    constructor(requestTracker: RequestTracker) {
        this.requestTracker = requestTracker;
        this.init();
    }

    init() {
        window.addEventListener('load', () => {
            let domContentLoadedTime = 0;
            let loadTime = 0;

            if (performance.getEntriesByType !== undefined) {
                const perfEntries = performance.getEntriesByType('navigation');
                if (perfEntries.length > 0) {
                    const navigationEntry = perfEntries[0];
                    const { domContentLoadedEventStart, loadEventStart, fetchStart } = navigationEntry as PerformanceNavigationTiming;
                    // dom树构建完成后触发 DOMContentLoaded事件
                    domContentLoadedTime = domContentLoadedEventStart - fetchStart;

                    // 页面完整的加载时间
                    loadTime = loadEventStart - fetchStart;
                }
            } else {
                const { fetchStart, domContentLoadedEventStart, loadEventStart } = performance.timing;
                domContentLoadedTime = domContentLoadedEventStart - fetchStart;
                loadTime = loadEventStart - fetchStart;
            }

            const log: TimingLog = {
                type: 'timing',
                DOMContentLoadedTime: domContentLoadedTime,
                loadTime
            };
            this.requestTracker.request(log);
        });
    }
}
